package com.club.football.utils;



import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.club.football.dto.UsersDto;
import com.club.football.entity.User;
import lombok.extern.log4j.Log4j;


/**
 * jwt助手
 *
 * @author gh
 * @date 2023/09/14
 */

@Log4j
public class JwtHelper {
    private JwtHelper() {
    }

    /**
     * 令牌签名密钥
     */
    private static final String TOKEN_SIGN_KEY = "6666";

    /**
     * 创建令牌
     *
     * @param user 用户
     * @return {@link String}
     */
    public static String createToken(User user) {
        return JWT.create()
                .setPayload("userId", user.getUserId())
                .setPayload("name", user.getName())
                .setPayload("code", user.getCode())
                .setKey(TOKEN_SIGN_KEY.getBytes())
                .sign();
    }

    /**
     * 获取用户标识
     *
     * @param token 令 牌
     * @return {@link Long}
     */
    public static Object getValue(String token, String key) {
        try {
            if (StringUtils.isBlank(token)) {
                return null;
            }
            JWT jwt = JWT.of(token);
            return jwt.getPayload(key).toString();
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }

    /**
     * 获取用户
     *
     * @param token 令牌
     * @return {@link UsersDto}
     */
    public static UsersDto getUser(String token) {
        try {
            if (StringUtils.isBlank(token)) {
                return null;
            }
            JWT jwt = JWT.of(token);
            UsersDto usersDto = new UsersDto();
            usersDto.setUserId(Long.valueOf(jwt.getPayload("userId").toString()));
            usersDto.setName((String) jwt.getPayload("name"));
            usersDto.setCode((String) jwt.getPayload("code"));
            return usersDto;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
    }


    /**
     * 检查令牌
     *
     * @param token 令 牌
     * @return boolean
     */
    public static boolean checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return Boolean.FALSE;
        }
        return JWT.of(token).setKey(TOKEN_SIGN_KEY.getBytes()).verify();
    }
}
